//
//  ConsultingViewController.m
//  HuiKaoClient
//
//  Created by 龚 杰 on 13-2-20.
//  Copyright (c) 2013年 龚 杰. All rights reserved.
//

#import "ConsultingViewController.h"
#import "MainTabBarController.h"
#import <QuartzCore/QuartzCore.h>
#import "ConsultingCell.h"
#import "AppDelegate.h"

#define kStatusBarHeight 20
#define kDefaultToolbarHeight 40
#define kKeyboardHeightPortrait 216
#define kKeyboardHeightLandscape 140
#define EOFFH 19
#define setOFFH 30


@interface ConsultingViewController ()

@end

@implementation ConsultingViewController
@synthesize inputToolbar;


- (id)init{
    if (self = [super init]) {
        m_ConsultingDataArray = [[NSMutableArray alloc] init];
        m_ConsultingCellArray = [[NSMutableArray alloc] init];
        m_page = 1;
        isLook = YES;
        isRefresh = NO;

    }
    return self;
}
-(void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    /* Listen for keyboard */
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    // 键盘高度变化通知，ios5.0新增的
#ifdef __IPHONE_5_0
    float version = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (version >= 5.0) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
    }
#endif
    MainTabBarController* tMainTabController = (MainTabBarController*)self.navigationController.tabBarController;
    tMainTabController.mainselectedIndex =  tMainTabController.selectedIndex;
    if ([m_RefreshBttBarItem superview] == nil) {
        [self.navigationController.navigationBar addSubview:m_RefreshBttBarItem];
    }

}
- (void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    /* No longer listen for keyboard */
	[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
	[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
    [m_RefreshBttBarItem removeFromSuperview];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    if([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {
        if ([self.navigationController.navigationBar viewWithTag:0x300] == nil) {
            UIImageView* tImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"titleBar.png"]];
            tImgView.tag =0x300;
            tImgView.frame = CGRectMake(0, 0, 320, 44);
            UILabel* title = [MainTabBarController setTitle:@"在线咨询"];
            [self.navigationController.navigationBar addSubview:tImgView];
            [self.navigationController.navigationBar addSubview:title];
            [tImgView release];
        }
    }
    m_RefreshBttBarItem = [UIButton buttonWithType:UIButtonTypeCustom];
    [m_RefreshBttBarItem setImage:[UIImage imageNamed:@"refresh.png"] forState:UIControlStateNormal];
    m_RefreshBttBarItem.frame =CGRectMake(280, 10, 24, 24);
    [m_RefreshBttBarItem addTarget:self action:@selector(RefreshBttPressed) forControlEvents:UIControlEventTouchUpInside];
    [m_RefreshBttBarItem retain];
    m_CLTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height-49-44-44) style:UITableViewStylePlain];
    [m_CLTableView setBackgroundColor:[UIColor clearColor]];
    m_CLTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    m_CLTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    m_CLTableView.dataSource =self;
    m_CLTableView.delegate = self;
    [self.view addSubview:m_CLTableView];
    
    m_refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - m_CLTableView.bounds.size.height, m_CLTableView.bounds.size.width, m_CLTableView.bounds.size.height)];
    m_refreshHeaderView.delegate = self;
    [m_CLTableView addSubview:m_refreshHeaderView];
    [m_refreshHeaderView refreshLastUpdatedDate];
    
    self.inputToolbar = [[UIInputToolbar alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-44-44-49, 320, 44)];
    [self.view addSubview:self.inputToolbar];
    inputToolbar.delegate = self;
    inputToolbar.textView.placeholder = @"输入内容";
    
    MainTabBarController* tMainTabController = (MainTabBarController*)self.navigationController.tabBarController;
    if ( tMainTabController.m_UserDic != nil) {
        NSUserDefaults* tUserDef = [NSUserDefaults standardUserDefaults];
        m_Userid = [tUserDef objectForKey:USER_ID];
        m_url = [tUserDef objectForKey:USER_AVATAR];
    }else{
        m_Userid = @"0";
        m_url = @"";
    }
#if TARGET_IPHONE_SIMULATOR
    NSLog(@"run on simulator");
    m_UDID = @"26391d4eb8ccb3637cfac24446cedb9e7dda896f";
#else
    NSLog(@"run on device");
    m_UDID = [UIDevice currentDevice].uniqueIdentifier;
#endif
    [m_UDID retain];
    [self requestPageData];
    [self addHudLoad];
    
}
- (void)RefreshBttPressed
{
    m_page = 1;
    [self requestPageData];
    [self addHudLoad];
         isRefresh = YES;
}
- (void)requestPageData
{
    if (isLook) {
        isLook = NO;
        HttpInterfaceManager* iHttpInterface = [HttpInterfaceManager sharedManager];
        iHttpInterface.delegate = self;
        [iHttpInterface GetConsultingLsitRequestGet:m_Userid UDID:m_UDID page:[NSNumber numberWithInt:m_page].stringValue pagenum:@"20"];
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
//{
//    CGRect screenFrame = [[UIScreen mainScreen] applicationFrame];
//    CGRect r = self.inputToolbar.frame;
//	if (UIInterfaceOrientationIsPortrait(toInterfaceOrientation))
//    {
//        r.origin.y = screenFrame.size.height - self.inputToolbar.frame.size.height - kStatusBarHeight;
//        if (keyboardIsVisible) {
//            r.origin.y -= kKeyboardHeightPortrait;
//        }
//        [self.inputToolbar.textView setMaximumNumberOfLines:13];
//	}
//	else
//    {
//        r.origin.y = screenFrame.size.width - self.inputToolbar.frame.size.height - kStatusBarHeight;
//        if (keyboardIsVisible) {
//            r.origin.y -= kKeyboardHeightLandscape;
//        }
//        [self.inputToolbar.textView setMaximumNumberOfLines:7];
//        [self.inputToolbar.textView sizeToFit];
//    }
//    self.inputToolbar.frame = r;
//}

#pragma mark -
#pragma mark Notifications

- (void)keyboardWillShow:(NSNotification *)notification
{
    NSDictionary *userInfo = [notification userInfo];
    
    // Get the origin of the keyboard when it's displayed.
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    // Get the top of the keyboard as the y coordinate of its origin in self's view's coordinate system. The bottom of the text view's frame should align with the top of the keyboard's final position.
    CGRect keyboardRect = [aValue CGRectValue];
    /* Move the toolbar to above the keyboard */
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.3];
	CGRect frame = self.inputToolbar.frame;
    CGRect frame1 = m_CLTableView.frame;
    if (UIInterfaceOrientationIsPortrait(self.interfaceOrientation)) {
        
        frame.origin.y = self.view.frame.size.height - frame.size.height - keyboardRect.size.height + 50;
        frame1.size.height = self.view.frame.size.height - frame.size.height - keyboardRect.size.height + 50;
       
    }
    else {
        frame.origin.y = self.view.frame.size.width - frame.size.height - kKeyboardHeightLandscape -  keyboardRect.size.height +50;
        frame1.size.height = self.view.frame.size.width - frame.size.height - kKeyboardHeightLandscape -  keyboardRect.size.height +50;
    }
	self.inputToolbar.frame = frame;
    m_CLTableView.frame =frame1;
	[UIView commitAnimations];
    keyboardIsVisible = YES;
        //当在底部是在滚动
    if ([m_ConsultingCellArray count]>0) {
        [m_CLTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[m_ConsultingCellArray count]-1 inSection:0]
                             atScrollPosition:UITableViewScrollPositionBottom
                                     animated:YES];
    }

}

- (void)keyboardWillHide:(NSNotification *)notification
{
    /* Move the toolbar back to bottom of the screen */
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.3];
	CGRect frame = self.inputToolbar.frame;
    CGRect frame1 = m_CLTableView.frame;

    if (UIInterfaceOrientationIsPortrait(self.interfaceOrientation)) {
        frame.origin.y = self.view.frame.size.height - frame.size.height;
        frame1.size.height = self.view.frame.size.height - frame.size.height;
    }
    else {
        frame.origin.y = self.view.frame.size.width - frame.size.height;
        frame1.size.height = self.view.frame.size.height - frame.size.height;
    }
	self.inputToolbar.frame = frame;
    m_CLTableView.frame =frame1;
	[UIView commitAnimations];
    keyboardIsVisible = NO;
 
}
#pragma mark UIInputToolbarDelegate
-(void)inputButtonPressed:(NSString *)inputText
{
    /* Called when toolbar button is pressed */
    NSLog(@"Pressed button with text: '%@'", inputText);

    NSDictionary* dic = [NSDictionary dictionaryWithObjectsAndKeys:m_url,@"avatar",inputText,@"message",@"q",@"type" ,nil];
    [self CreateCell:dic];
    HttpInterfaceManager* iHttpInterface = [HttpInterfaceManager sharedManager];
    iHttpInterface.delegate = self;
    [iHttpInterface SendConsultingRequestPost:m_Userid UDID:m_UDID message:inputText];
    [self addHudLoad];
    
}
#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"%d", [m_ConsultingCellArray count]);
    return [m_ConsultingCellArray count];
}
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableVie
//{
//    return 1;
//}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    ConsultingCell* tCell = [m_ConsultingCellArray objectAtIndex:indexPath.row];
    return tCell;
}

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//
//    UIView* tSectionHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 30)];
//    [tSectionHeaderView setBackgroundColor:[UIColor clearColor]];
//    UILabel* tLab = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 300, 20)];
//    [tLab setBackgroundColor:[UIColor clearColor]];
//    [tLab setFont:[UIFont boldSystemFontOfSize:15]];
//    [tLab setTextColor:[UIColor colorWithRed:125/250.f green:125/255.0f blue:125/255.0f alpha:1.0]];
//    [tLab setText:@"设置要提醒的考试"];
//    [tSectionHeaderView addSubview:tLab];
//    [tLab release];
//    return [tSectionHeaderView autorelease];
//}

#pragma mark UITableViewDelegate
//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//{
//    return 30;
//}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ConsultingCell* tCell = (ConsultingCell*)[m_ConsultingCellArray objectAtIndex:indexPath.row];
    return tCell.height;
}

#pragma mark MBProgressHUDDelegate
- (void)hudWasHidden:(MBProgressHUD *)hud{
    m_MBHUD.delegate = nil;
	[m_MBHUD removeFromSuperview];
	[m_MBHUD release];
	m_MBHUD=nil;
}

-(void) addHudLoad{
	if (m_MBHUD == nil) {
		m_MBHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
		// Add HUD to screen
        AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
		[tAppDel.window addSubview:m_MBHUD];
		// Regisete for HUD callbacks so we can remove it from the window at the right time
		m_MBHUD.delegate = self;
		m_MBHUD.labelText = @"请求数据中...";
		[m_MBHUD show:YES];
	}
}
#pragma mark -
#pragma mark UIScrollViewDelegate Methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	
	[m_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    int tShowH =0;
    if ([scrollView isEqual:m_CLTableView]) {
        [m_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
        tShowH = scrollView.contentOffset.y+scrollView.frame.size.height;
        if (scrollView.contentOffset.y > 0&&tShowH > scrollView.contentSize.height+60&&isLook) {
             [inputToolbar.textView resignFirstResponder];
            m_page = 1;
            [self requestPageData];
            isRefresh = YES;
        }
    }
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	
	[self reloadTableViewDataSource];
    [inputToolbar.textView resignFirstResponder];
    m_page++;
    [self requestPageData];

}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	
	return m_reloading; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	
	return [NSDate date]; // should return date data source was last changed
}

#pragma mark -
#pragma mark Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource{
	
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
	m_reloading = YES;
	
}
- (void)doneLoadingTableViewData{
	
	//  model should call this when its done loading
	m_reloading = NO;
	[m_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:m_CLTableView];
	
}
#pragma mark HttpInterfaceManageDelegate
-(void)RequestResultsSendConsulting:(NSDictionary*)dic;
{
   [self hudWasHidden:m_MBHUD];
    if (dic!=nil) {
        NSInteger result = ((NSString*)[dic objectForKey:@"result"]).integerValue;
        if (result == 1) {
            AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
            [tAppDel showWithCustomView:@"提示" detailText:@"发送成功" isCue:YES delayTime:2.0f];
        }else{
            AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
            [tAppDel showWithCustomView:@"提示" detailText:@"发送失败" isCue:YES delayTime:2.0f];
        }
    }
   
}
-(void)RequestResultsGetConsultingList:(NSArray*)dic
{
    [self hudWasHidden:m_MBHUD];
    [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:0.2f];
    if (isRefresh) {
        [m_ConsultingDataArray removeAllObjects];
        [m_ConsultingCellArray removeAllObjects];
    }
    if ([dic count]>0) {
            [self initCell:dic];
    }else{
        if (m_page >1) {
            m_page--;
        }
    }
    isRefresh =NO;
    isLook = YES;
}
-(void)RequestResultsErrer:(NSDictionary*)dic
{
    [self hudWasHidden:nil];
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [tAppDel showWithCustomView:@"提示" detailText:[dic objectForKey:@"error_msg"] isCue:YES delayTime:2.0f];
    isRefresh =NO;
    isLook = YES;
}

- (void)CreateCell:(NSDictionary*)dic
{
    
    ConsultingCell* tCell = [[ConsultingCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"afas" ];
    tCell.accessoryType = UITableViewCellAccessoryNone;
    tCell.selectionStyle = UITableViewCellSelectionStyleNone;
    tCell.frame = CGRectMake(0, 0, self.view.frame.size.width, tCell.height);
    [tCell initDirection:dic];
    [m_ConsultingDataArray addObject:dic];
    [m_ConsultingCellArray addObject:tCell];
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    CGPoint Offset = m_CLTableView.contentOffset;
    Offset.y += tCell.height;
    m_CLTableView.contentOffset = Offset;
    [UIView commitAnimations];
    [m_CLTableView reloadData];
    
}
- (void)initCell:(NSArray*)iArray
{
    NSInteger index = 0;
    if (m_page == 1) {
        for (NSDictionary* dic1 in iArray) {
            ConsultingCell* tCell = [[ConsultingCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"afas" ];
            tCell.accessoryType = UITableViewCellAccessoryNone;
            tCell.selectionStyle = UITableViewCellSelectionStyleNone;
            tCell.frame = CGRectMake(0, 0, self.view.frame.size.width, tCell.height);
            [tCell initDirection:dic1];
            [m_ConsultingDataArray addObject:dic1];
            [m_ConsultingCellArray addObject:tCell];
            index++;
        }
        [m_CLTableView reloadData];
    }else{
        for (int i = [iArray count]-1 ;i >= 0 ;--i) {
            NSDictionary* dic1 = [iArray objectAtIndex:i];
            ConsultingCell* tCell = [[ConsultingCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"afas" ];
            tCell.accessoryType = UITableViewCellAccessoryNone;
            tCell.selectionStyle = UITableViewCellSelectionStyleNone;
            tCell.frame = CGRectMake(0, 0, self.view.frame.size.width, tCell.height);
            
            [tCell initDirection:dic1];
            [m_ConsultingDataArray insertObject:tCell atIndex:0];
            [m_ConsultingCellArray insertObject:tCell atIndex:0];
            index++;
        }
        [m_CLTableView reloadData];
        //当在底部是在滚动
        if ([m_ConsultingCellArray count]>0) {
            NSIndexPath* indexpath =   [NSIndexPath indexPathForRow:index inSection:0];
            [m_CLTableView scrollToRowAtIndexPath:indexpath
                                 atScrollPosition:UITableViewScrollPositionBottom
                                         animated:YES];
        }
    }
}

- (void)dealloc
{
    [m_RefreshBttBarItem release];
    [inputToolbar release];
    [m_CLTableView release];
    [m_ConsultingDataArray release];
    [m_ConsultingCellArray release];
    [m_refreshHeaderView release];
    [m_UDID release];
    m_MBHUD = nil;
    [super dealloc];
}
@end
